<template>
  <div>
    <el-form ref="blogForm" :model="blogForm" label-width="80px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="标题">
            <el-input v-model="blogForm.title"></el-input>
          </el-form-item>
          <el-form-item label="简介">
            <el-input v-model="blogForm.summary"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="封面图">
            <el-upload
              class="avatar-uploader"
              action=""
              accept=".png,.jpg"
              :on-change="onTitlePicSelected"
              :auto-upload="false"
              :show-file-list="false">
              <el-image class="avatar-img" v-if="blogForm.titlePic" :src="blogForm.titlePic" fit="cover"></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="内容">
        <div style="height: 500px;border-radius: 2px;border: 1px solid #d9d9d9;">
          <mavon-editor
            ref=md
            @imgAdd="imgAdd"
            @imgDel="imgDel"
            @save="updateBlog"
            @change="onContentChange"
            v-model="blogForm.content"
            toolbarsBackground="#F8F8F8"
            :boxShadow="false"
            :toolbars="toolbars"
            style="height: 460px;">
          </mavon-editor>
          <div style="float: right;margin-right: 20px;">
            <span style="margin-right: 10px">段落：{{ paragraphs }}</span>
            <span>字符：{{ wordage }}</span>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div style="float: right;">
      <el-button size="medium" @click="updateBlog">保存</el-button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import {blogApi} from '@/api/BlogApi'

Vue.use(mavonEditor)

export default {
  created () {
    const blogId = this.$route.query.blogId
    blogApi.getBlogById({blogId: blogId}).then((res) => {
      if (this.$http.isSuccess(res)) {
        this.blogForm = res.data
      }
    }).catch(() => {
      this.$message.error('查询失败')
    })
  },

  mounted () {
    console.log('4. 挂载到实例')
    this.blogForm.content += ' '
  },

  data () {
    return {
      blogForm: {content: ''},
      paragraphs: 0,
      wordage: 0
    }
  },
  methods: {
    // 标题图选中时调用
    onTitlePicSelected (file) {
      this.blogForm.titlePic = URL.createObjectURL(file.raw)
      this.blogForm.titlePicFile = file.raw
    },
    // 文件添加后调用
    imgAdd (pos, file) {
      const formData = new FormData()
      formData.append('imageFile', file)
      blogApi.uploadImage(formData).then((res) => {
        if (this.$http.isSuccess(res)) {
          const url = res.data
          this.$refs.md.$img2Url(pos, url)
          this.$message.success('图片添加成功')
        }
      }).catch(() => {
        this.$message.error('图片添加失败')
      })
    },

    // 文件删除后调用
    imgDel (fileInfoArr) {
      blogApi.deleteImage({url: fileInfoArr[0]}).then((res) => {
        if (this.$http.isSuccess(res)) {
          this.$message.success('图片移除成功')
        }
      }).catch(() => {
        this.$message.error('图片移除失败')
      })
    },

    // blog内容编辑修改调用
    onContentChange () {
      let content = this.blogForm.content
      if (content && content.length > 0) {
        this.wordage = content.length
        let contentSplit = content.split(/\r\n|\r|\n/)
        console.log(contentSplit)
        contentSplit = contentSplit.filter(function (s) {
          return !!(s && s.trim().length > 0)
        })
        this.paragraphs = contentSplit.length
      }
    },

    /**
     * 对象转化为formdata
     * @param {Object} object
     */
    getFormData (object) {
      const formData = new FormData()
      Object.keys(object).forEach(key => {
        const value = object[key]
        if (Array.isArray(value)) {
          value.forEach((subValue, i) =>
            formData.append(key + `[${i}]`, subValue)
          )
        } else {
          formData.append(key, object[key])
        }
      })
      return formData
    },

    // 更新blog
    updateBlog () {
      const formData = this.getFormData(this.blogForm)
      blogApi.updateBlogInfo(formData).then((res) => {
        if (this.$http.isSuccess(res)) {
          this.$message.success('博客修改成功')
        }
      }).catch(() => {
        this.$message.error('博客修改失败')
      })
    }
  },
  computed: {
    toolbars () {
      return {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true // 预览
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  width: 200px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-img {
  background-color: white;
  width: 100%;
  height: 100%;
  vertical-align: middle;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 100px;
  text-align: center;
}
</style>
